package com.example.chcrm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.chcrm.entity.common.*;
import com.example.chcrm.entity.employee.Department;
import com.example.chcrm.entity.employee.EmployeeVo;
import com.example.chcrm.entity.employee.SupplierPort;
import com.example.chcrm.entity.supplier.HighwaySupplierCar;
import com.example.chcrm.entity.supplier.HighwaySupplierInfo;
import com.example.chcrm.entity.vehicle.TransportChildCv;
import com.example.chcrm.entity.vehicle.TransportPlanCv;
import com.example.chcrm.entity.vehicle.VehicleDeployCarCv;
import com.example.chcrm.entity.vehicle.VehicleDeployFleetCv;
import com.example.chcrm.mapper.*;
import com.example.chcrm.service.VehicleDeployFleetCvService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

/**
 * @Author 邹
 * @Date 2025/4/26 15:36
 * @Version 1.0
 */
@Service
public class VehicleDeployFleetCvServiceImpl <T> implements VehicleDeployFleetCvService<T> {
    @Autowired
    private VehicleDeployFleetCvMapper fleetCvMapper;   //公路供应商任务主表
    @Autowired
    private VehicleDeployCarCvMapper carCvMapper;   //公路供应商调配委托车表
    @Autowired
    private HighwaySupplierInfoMapper highwaySupplierInfoMapper;    //公路供应商mapper
    @Autowired
    private HighwaySupplierCarMapper highwaySupplierCarMapper;      //运输车信息mapper
    @Autowired
    private TransportPlanCvMapper planCvMapper;
    @Autowired
    private TransportChildCvMapper transportChildMapper;          //运输计划委托车
    @Autowired
    private LineConfigMapper lineConfigMapper;          //线路设置主表
    @Autowired
    private OperateRecordMapper operateRecordMapper;    //操作日志mapper
    @Autowired
    private TAreaMapper tAreaMapper;        //地址区域Mapper
    @Autowired
    private SupplierPortMapper supplierPortMapper;  //港口Mappper
    @Autowired
    private TransportPlanCvMapper transportPlanCvMapper;
//    @Autowired
//    private VehicleDeployCarCvMapper vehicleDeployCarCvMapper;//委托车调配id

    @Override
    public ResponseMsg<IPage<VehicleDeployFleetCv>> pageList(VehicleDeployFleetCv fleet) {
        QueryWrapper<VehicleDeployFleetCv> query = new QueryWrapper<>();
//        if (empVo.getEmptype().equals("SUPPLER")) {//供应商只能看自己的
//            query.eq("fleet_id", empVo.getHighwaySupplierInfo().getId());
//        } else {
        if (StringUtils.isNotBlank(fleet.getFleetName())) {
            query.like("fleet_name", fleet.getFleetName());
        }
//        }
        if (StringUtils.isNotBlank(fleet.getStartName())) {
            query.like("start_name", fleet.getStartName());
        }
        if (StringUtils.isNotBlank(fleet.getDeliveryPortName())) {
            query.like("delivery_port_name", fleet.getDeliveryPortName());
        }
        if (StringUtils.isNotBlank(fleet.getDeliveryName())) {
            query.like("delivery_name", fleet.getDeliveryName());
        }
        if (StringUtils.isNotBlank(fleet.getStartPortName())) {
            query.like("start_port_name", fleet.getStartPortName());
        }
//        if (StringUtils.isNotBlank(fleet.getStartTime())) {
//
//            if (!fleet.getStartTime().equals("null")){
//                query.ge("entruck_time", fleet.getStartTime());
//            }
//        }
//        if (StringUtils.isNotBlank(fleet.getEndTime())) {
//            if (!fleet.getEndTime().equals("null")){
//                query.le("entruck_time", fleet.getEndTime());
//            }
//
//        }
        if (fleet.getStatus() != null) {
            query.eq("status", fleet.getStatus());
        }
        query.orderByDesc("create_time");
        List<VehicleDeployFleetCv> list = fleetCvMapper.selectList(query);
        ResponseMsg<IPage<VehicleDeployFleetCv>> iPageResponseMsg = new ResponseMsg<>();
        Page<VehicleDeployFleetCv> page = new Page<>();
        page.setRecords(list);
        page.setTotal(list.size());
        page.setSize(fleet.getRows());
        page.setCurrent(fleet.getPage());
        iPageResponseMsg.setData(page);
        iPageResponseMsg.success("查询成功");
        return iPageResponseMsg;
    }

    @Override
    public ResponseMsg<Object> detail(String id) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        //查询供应商任务
        VehicleDeployFleetCv deployFleet = fleetCvMapper.selectById(id);
        if (deployFleet != null) {
            //查询卸车数量
//            List<VehicleDeployCarCv> carCvs = carCvMapper.deliveryPlace(deployFleet.getId());
            deployFleet.setCarList(carCvMapper.selectList(new QueryWrapper<VehicleDeployCarCv>().eq("basic_id", deployFleet.getId())
                    .eq("is_deleted", 0)));
            //查询操作记录
            List<OperateRecord> operateRecordList = operateRecordMapper.selectList(new QueryWrapper<OperateRecord>()
                    .eq("sourceId", deployFleet.getId())
                    .orderByDesc("create_time"));
            deployFleet.setOperateRecordList(operateRecordList);
        }
        msg.success("查询成功");
        msg.setData(deployFleet);
        return msg;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseMsg<Object> add(VehicleDeployFleetCv vehicleDeploy, EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        HighwaySupplierCar highwaySupplierCar  =highwaySupplierCarMapper.selectOne(new QueryWrapper<HighwaySupplierCar>()
                .eq("license",vehicleDeploy.getTruckName()).eq("driver_name",vehicleDeploy.getDriverName()));
        if (highwaySupplierCar ==null){
            msg.fail("操作失败，车辆不存在");
            return msg;
        }

        //验证起始位置是否存在
        if (vehicleDeploy.getStartType() == 1) {
//            SupplierPort supplierPort = supplierPortMapper.selectById(vehicleDeploy.getStartPortId());
            SupplierPort supplierPort = supplierPortMapper.selectOne(new QueryWrapper<SupplierPort>()
                    .eq("port_name",vehicleDeploy.getStartPortName()));
            if (supplierPort == null || supplierPort.getIsDeleted() != BasicDoc.NOT_DELETE) {
                msg.fail("操作失败，起始港不存在");
                return msg;
            }
            vehicleDeploy.setStartId(supplierPort.getAreaId());
            vehicleDeploy.setStartFullId(supplierPort.getAreaFullId());
            vehicleDeploy.setStartName(supplierPort.getArea());
            vehicleDeploy.setStartCoordinate(supplierPort.getCoordinate());
            vehicleDeploy.setStartPortId(supplierPort.getId());
            vehicleDeploy.setStartPortName(supplierPort.getPortName());
        } else {
//            TArea tArea = tAreaMapper.selectById(vehicleDeploy.getStartName());
            TArea tArea = tAreaMapper.selectOne( new QueryWrapper<TArea>()
                    .eq("parent_name_lis",vehicleDeploy.getStartName()) );
            if (tArea == null) {
                msg.fail("操作失败，起始区域不存在");
                return msg;
            }
            vehicleDeploy.setStartId(tArea.getAdCode());
            vehicleDeploy.setStartFullId(tArea.getParentCodeLis());
            vehicleDeploy.setStartName(tArea.getParentNameLis());
            vehicleDeploy.setStartCoordinate(tArea.getCenter());
            vehicleDeploy.setStartPortId(null);
            vehicleDeploy.setStartPortName(null);
        }
        String deployFleetId = "";
        Map<String, List<VehicleDeployCarCv>> carCvMap = new HashMap<>();
        VehicleDeployFleetCv deployFleet = vehicleDeploy;
            //查询供应商是否存在
//            HighwaySupplierInfo highwaySupplier = highwaySupplierInfoMapper.selectById(deployFleet.getFleetId());
            HighwaySupplierInfo highwaySupplier = highwaySupplierInfoMapper.selectOne(
                    new QueryWrapper<HighwaySupplierInfo>().eq("name",deployFleet.getFleetName())
                            .eq("status",1)
            );
            if (highwaySupplier == null || highwaySupplier.getIsDeleted() != BasicDoc.NOT_DELETE) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                msg.fail("供应商不存在");
                return msg;
            }
        deployFleet.setFleetId(highwaySupplier.getId());
            if (highwaySupplier.getStatus() != 1) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                msg.fail("供应商必须是合作中");
                return msg;
            }
            int num = deployFleetId.indexOf(highwaySupplier.getId());
            if (num > 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                msg.fail("供应商不能重复");
                return msg;
            }
                //验证交车地
                if (deployFleet.getDeliveryType() == 0) {
//                    TArea tArea = tAreaMapper.selectById(deployFleet.getDeliveryId());
                    TArea tArea = tAreaMapper.selectOne( new QueryWrapper<TArea>()
                            .eq("parent_name_lis",vehicleDeploy.getDeliveryName()) );
                    if (tArea == null) {
                        msg.fail("操作失败，交车区域不存在");
                        return msg;
                    }
                    deployFleet.setDeliveryId(tArea.getAdCode());
                    deployFleet.setDeliveryFullId(tArea.getParentCodeLis());
                    deployFleet.setDeliveryName(tArea.getParentNameLis());
                    deployFleet.setDeliveryCoordinate(tArea.getCenter());
                    deployFleet.setDeliveryPortId(null);
                    deployFleet.setDeliveryPortName(null);
                } else {
                    SupplierPort supplierPort = supplierPortMapper.selectOne(new QueryWrapper<SupplierPort>()
                            .eq("port_name",vehicleDeploy.getDeliveryPortName()));
//                    SupplierPort supplierPort = supplierPortMapper.selectById(deployFleet.getDeliveryPortId());
                    if (supplierPort == null || supplierPort.getIsDeleted() != BasicDoc.NOT_DELETE) {
                        msg.fail("操作失败，交车港不存在");
                        return msg;
                    }
                    deployFleet.setDeliveryId(supplierPort.getAreaId());
                    deployFleet.setDeliveryFullId(supplierPort.getAreaFullId());
                    deployFleet.setDeliveryName(supplierPort.getArea());
                    deployFleet.setDeliveryCoordinate(supplierPort.getCoordinate());
                    deployFleet.setDeliveryPortId(supplierPort.getId());
                    deployFleet.setDeliveryPortName(supplierPort.getPortName());
                }
                //验证线路是否存在
                QueryWrapper<LineConfig> lineConfigQueryWrapper = new QueryWrapper<>();
                lineConfigQueryWrapper.eq("line_type", 1);
                lineConfigQueryWrapper.eq("is_deleted", 0);
                //起始区域
                if (deployFleet.getStartId() != null) {
                    lineConfigQueryWrapper.eq("start_address_id", vehicleDeploy.getStartId());
                } else {
                    lineConfigQueryWrapper.isNull("start_address_id");
                }
                if (deployFleet.getStartPortId() != null) {
                    lineConfigQueryWrapper.eq("departure_port_id", vehicleDeploy.getStartPortId());
                } else {
                    lineConfigQueryWrapper.isNull("departure_port_id");
                }
                //交车区域
                if (deployFleet.getDeliveryId() != null) {
                    lineConfigQueryWrapper.eq("end_address_id", deployFleet.getDeliveryId());
                } else {
                    lineConfigQueryWrapper.isNull("end_address_id");
                }
                if (deployFleet.getDeliveryPortId() != null) {
                    lineConfigQueryWrapper.eq("arrive_port_id", deployFleet.getDeliveryPortId());
                } else {
                    lineConfigQueryWrapper.isNull("arrive_port_id");
                }
                LineConfig lineConfig = lineConfigMapper.selectOne(lineConfigQueryWrapper);
                if (lineConfig == null) {
                    //起始港为空 交车港不为空
                    if (StringUtils.isBlank(vehicleDeploy.getStartPortName()) && StringUtils.isNotBlank(deployFleet.getDeliveryPortName())) {
                        msg.fail("线路：" + vehicleDeploy.getStartName() + "——" + deployFleet.getDeliveryName() + " " + deployFleet.getDeliveryPortName() + "不存在");
                        return msg;
                        //起始港不为空 交车港为空
                    } else if (StringUtils.isNotBlank(vehicleDeploy.getStartPortName()) && StringUtils.isBlank(deployFleet.getDeliveryPortName())) {
                        msg.fail("线路：" + vehicleDeploy.getStartName() + " " + vehicleDeploy.getStartPortName() + "——" + deployFleet.getDeliveryName() + " " + "不存在");
                        return msg;
                        //两个都为空
                    } else if (StringUtils.isBlank(vehicleDeploy.getStartPortName()) && StringUtils.isBlank(deployFleet.getDeliveryPortName())) {
                        msg.fail("线路：" + vehicleDeploy.getStartName() + "——" + deployFleet.getDeliveryName() + "不存在");
                        return msg;
                    } else {
                        msg.fail("线路：" + vehicleDeploy.getStartName() + " " + vehicleDeploy.getStartPortName() + "——" + deployFleet.getDeliveryName() + " " + deployFleet.getDeliveryPortName() + "不存在");
                        return msg;
                    }

                }
            deployFleet.setId(RandomHelper.uuid());
            deployFleet.setSurplusCount(0); //实际装车数量
            deployFleet.setSurdownCount(0);
            deployFleet.setTruckId(highwaySupplierCar.getId());
            deployFleet.setTruckName(highwaySupplierCar.getLicense());
            deployFleet.setStartType(vehicleDeploy.getStartType());
            deployFleet.setStartId(vehicleDeploy.getStartId());
            deployFleet.setStartFullId(vehicleDeploy.getStartFullId());
            deployFleet.setStartName(vehicleDeploy.getStartName());
            deployFleet.setStartCoordinate(vehicleDeploy.getStartCoordinate());
            deployFleet.setStartPortId(vehicleDeploy.getStartPortId());
            deployFleet.setStartPortName(vehicleDeploy.getStartPortName());
            deployFleet.setStatus(0);
            deployFleet.setIsDeleted(BasicDoc.NOT_DELETE);
            deployFleet.setCreateTime(new Date());
            fleetCvMapper.insert(deployFleet);

            //添加操作日志
            OperateRecord ope = new OperateRecord();
            ope.setId(RandomHelper.uuid());
            ope.setOperateType(OperateRecord.OPE_ADD);
            ope.setSourceId(deployFleet.getId());
            if (empVo!=null){
                ope.setOperationName(empVo.getEmpNm());
                ope.setOperationId(empVo.getId());
            }
            operateRecordMapper.insert(ope);

            highwaySupplierCar.setStatus(1);
            highwaySupplierCarMapper.updateById(highwaySupplierCar);
        msg.success("操作成功");
        return msg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> startLoading(VehicleDeployFleetCv operationDdeploy, EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<Object>();
        //--------------查询司机调配信息--------------
        VehicleDeployFleetCv oldDeployDriver = fleetCvMapper.selectById(operationDdeploy.getId());
        if (oldDeployDriver == null || oldDeployDriver.getIsDeleted() != BasicDoc.NOT_DELETE) {
            msg.fail("操作失败，车辆调配未找到");
            return msg;
        }
        if (oldDeployDriver.getStatus() != 0 && oldDeployDriver.getStatus() != 1) {
            msg.fail("操作失败，车辆调配状态必须是待开始或装车中");
            return msg;
        }
        //--------------查询供应商调配信息--------------
        //查港口
        Map<String,SupplierPort> portMap= supplierPortMapper.selectList(new QueryWrapper<SupplierPort>()
                .select("id,area_id,area_full_id,area,coordinate")
                .eq("status",1)
                .eq("is_deleted",0)).stream().collect(Collectors.toMap(SupplierPort::getId,p->p));
        /*if(deployFleet.getFleetCount() < (deployFleet.getSurplusCount() + operationDdeploy.getVehicleCarList().size())){
            msg.fail("操作失败，已超过供应商预装车数量");
            return msg;
        }*/
        //--------------剩余必装委托车数量--------------
//        int appointLoadingNum = carCvMapper.selectCount(new QueryWrapper<VehicleDeployCarCv>()
//                .eq("basic_id", operationDdeploy.getId())
//                .eq("state", 0)
//                .eq("is_deleted", BasicDoc.NOT_DELETE)).intValue();
        for (VehicleDeployCarCv deployCarTr : operationDdeploy.getCarList()) {
//            if (!StringUtils.isNotBlank(deployCarTr.getId())) {
//                msg.fail("装车失败，运输计划委托车id不能为空");
//                return msg;
//            }
            if (!StringUtils.isNotBlank(deployCarTr.getBatchNumber())) {
                msg.fail("装车失败，运输计划委托车批次号不能为空");
                return msg;
            }
            if (!StringUtils.isNotBlank(deployCarTr.getWaybillNo())) {
                msg.fail("装车失败，运输计划委托车运单号不能为空");
                return msg;
            }
            if (!StringUtils.isNotBlank(deployCarTr.getFrameNumber())) {
                msg.fail("装车失败，运输计划委托车车架号不能为空");
                return msg;
            }
            //--------------查询运输计划委托车--------------
//            TransportChildCv transportChild = transportChildMapper.selectById(deployCarTr.getId());
            TransportChildCv transportChild = transportChildMapper.selectOne(new QueryWrapper<TransportChildCv>()
                    .eq("batch_number",deployCarTr.getBatchNumber()).eq("waybill_no",deployCarTr.getWaybillNo())
                    .eq("frame_number",deployCarTr.getFrameNumber()).eq("is_deleted",0));
            if (transportChild == null || transportChild.getIsDeleted() != BasicDoc.NOT_DELETE) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                msg.fail("装车失败，运输计划委托车未找到");
                return msg;
            }
            if (!transportChild.getActualPositionId().equals(oldDeployDriver.getStartId())
                    || StringUtils.isEmpty(transportChild.getActualPositionId()) != StringUtils.isEmpty(oldDeployDriver.getStartId())
                    || (oldDeployDriver.getStartType() == 1 && !oldDeployDriver.getStartPortId().equals(transportChild.getActualPortId()))) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                msg.fail("装车失败，委托车未在当前位置");
                return msg;
            }
            if(transportChild.getActualPortId()!=null&&!transportChild.getActualPortId().equals(oldDeployDriver.getStartPortId())){  //港口比对
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                msg.fail("车架号:"+transportChild.getFrameNumber()+"未在当前位置");
                return msg;
            }
//            if (transportChild.getState() == 1) {
//                //-------------验证委托车是否分配给当前供应商-------------
//                VehicleDeployCarCv deployCar = carCvMapper.selectOne(new QueryWrapper<VehicleDeployCarCv>()
//                        .eq("car_id", transportChild.getId())
//                        .eq("basic_id", operationDdeploy.getId())
//                        .eq("is_deleted", BasicDoc.NOT_DELETE));
//                if (deployCar == null) {
//                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                    msg.fail("装车失败，委托车已分配给其它供应商");
//                    return msg;
//                }
//                if (deployCar.getState() != 0) {
//                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                    msg.fail("装车失败，委托车状态必须是待运输");
//                    return msg;
//                }
//                //-------------修改调配委托车信息-------------
//                deployCar.setPersonnelId(oldDeployDriver.getTruckId());
//                deployCar.setPersonnelName(oldDeployDriver.getTruckName());
//                DateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                Date date;
//                try {
//                    date = ft.parse(operationDdeploy.getStartTime());
//                } catch (Exception e) {
//                    date = null;
//                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                    msg.fail("装车时间异常");
//                    return msg;
//                }
//
//                deployCar.setLoadingDate(date);
//                deployCar.setState(1);
//                carCvMapper.updateById(deployCar);
//            } else
            DateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date;
            try {
                date = ft.parse(operationDdeploy.getStartTime());
            } catch (Exception e) {
                date = null;
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                msg.fail("装车时间异常");
                return msg;
            }
                if (transportChild.getState() == 0) {
                    VehicleDeployFleetCv deployFleet=oldDeployDriver;
                //新增调配委托车
                VehicleDeployCarCv deployCar = new VehicleDeployCarCv();
                deployCar.setId(RandomHelper.uuid());
                deployCar.setPlayId(transportChild.getBasicId());
                deployCar.setCarId(transportChild.getId());
                deployCar.setType(0);
                deployCar.setBasicId(deployFleet.getId());
                deployCar.setBatchNumber(transportChild.getBatchNumber());      //批次号
                deployCar.setWaybillNo(transportChild.getWaybillNo());          //运单编号
                deployCar.setFrameNumber(transportChild.getFrameNumber());      //车架号
                deployCar.setBrandId(transportChild.getBrandId());
                deployCar.setBrand(transportChild.getBrandName());
                deployCar.setModelId(transportChild.getModelId());
                deployCar.setModel(transportChild.getModelName());
                deployCar.setConfig(transportChild.getConfig());
                deployCar.setColor(transportChild.getColor());
                deployCar.setWeight(transportChild.getWeight());
                deployCar.setLwh(transportChild.getLwh());
                deployCar.setSupplierId(oldDeployDriver.getFleetId());
                deployCar.setSupplierName(oldDeployDriver.getFleetName());
                deployCar.setPersonnelId(oldDeployDriver.getTruckId());
                deployCar.setPersonnelName(oldDeployDriver.getTruckName());
                //----------装车位置----------
                deployCar.setStartType(oldDeployDriver.getStartType());       //起始类型 0：区域 1：港口
                deployCar.setStartId(oldDeployDriver.getStartId());           //起始地id
                deployCar.setStartFullId(oldDeployDriver.getStartFullId());   //起始地id(包含父级id)
                deployCar.setStartName(oldDeployDriver.getStartName());       //起始地区域名称
                deployCar.setStartCoordinate(oldDeployDriver.getStartCoordinate());
                deployCar.setStartPortId(oldDeployDriver.getStartPortId());       //起始港id
                deployCar.setStartPortName(oldDeployDriver.getStartPortName());   //起始港名
                //----------交车位置----------
                deployCar.setDeliveryType(oldDeployDriver.getDeliveryType());       //交车类型 1：港口
                deployCar.setDeliveryId(oldDeployDriver.getDeliveryId());
                deployCar.setDeliveryFullId(oldDeployDriver.getDeliveryFullId());
                deployCar.setDeliveryName(oldDeployDriver.getDeliveryName());
                deployCar.setDeliveryCoordinate(oldDeployDriver.getDeliveryCoordinate());
                deployCar.setDeliveryPortId(oldDeployDriver.getDeliveryPortId());
                deployCar.setDeliveryPortName(oldDeployDriver.getDeliveryPortName());


                deployCar.setLoadingDate(date);
                deployCar.setState(1);
                carCvMapper.insert(deployCar);
            } else if (transportChild.getState() == 2) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                msg.fail("装车失败，委托车运输中");
                return msg;
            } else if (transportChild.getState() == 3) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                msg.fail("装车失败，委托车已交车");
                return msg;
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                msg.fail("装车失败，委托车信息待完善");
                return msg;
            }
            //-------------修改计划委托车信息-------------
            if (transportChild.getIsOutStorage() == 0 || transportChild.getLoadingDate() == null) {
                transportChild.setIsOutStorage(1);
                transportChild.setLoadingDate(date);
            }
            transportChild.setState(2);
        }
        //-------------修改供应商调配-------------
        oldDeployDriver.setSurplusCount(oldDeployDriver.getSurplusCount() + operationDdeploy.getCarList().size());
        oldDeployDriver.setStatus(1);
        fleetCvMapper.updateById(oldDeployDriver);

        OperateRecord ope = new OperateRecord();
        ope.setId(RandomHelper.uuid());
        ope.setOperateType("添加装车");
        ope.setSourceId(operationDdeploy.getId());
        ope.setRemark(String.valueOf(operationDdeploy.getCarList().size()));
        if (empVo!=null){
            ope.setOperationName(empVo.getEmpNm());
            ope.setOperationId(empVo.getId());
        }
        operateRecordMapper.insert(ope);
        msg.success("手动装车成功");
        return msg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> fulfilTransport(VehicleDeployFleetCv newDeployDriver, EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<Object>();
        //验证司机调配是否存在
        VehicleDeployFleetCv deployDriver = fleetCvMapper.selectById(newDeployDriver.getId());
        if (deployDriver == null || deployDriver.getIsDeleted() != BasicDoc.NOT_DELETE) {
            msg.fail("操作失败，车辆调配未找到");
            return msg;
        }
        if (deployDriver.getStatus() != 1) {
            msg.fail("操作失败，车辆调配状态必须是执行中");
            return msg;
        }
        List<String> uodateCarCvList = new ArrayList<>();//批量更新调配委托车
        List<TransportChildCv> childCvs = new ArrayList<>();//更新计划委托车
        //查询调配委托车信息
        List<VehicleDeployCarCv> deployCarList = carCvMapper.selectList(new QueryWrapper<VehicleDeployCarCv>()
                .eq("basic_id", deployDriver.getId())
                .eq("state", 1)
                .eq("is_deleted", BasicDoc.NOT_DELETE));
        //批量查计划委托车
        List<TransportChildCv> transportChildCvs = transportChildMapper.batchTransportChildCvList(deployDriver.getId());//计划委托车
        List<TransportPlanCv> planCvList = planCvMapper.bctchQueryPlanList(deployDriver.getId());//计划
        ConcurrentMap<String, TransportChildCv> chlidCvMap = new ConcurrentHashMap<>();
        ConcurrentMap<String, TransportPlanCv> planCvMap = new ConcurrentHashMap<>();
        for (TransportChildCv c : transportChildCvs) {
            chlidCvMap.put(c.getId(), c);
        }
        for (TransportPlanCv p : planCvList) {
            planCvMap.put(p.getId(), p);
        }
        for (VehicleDeployCarCv deployCar : deployCarList) {
            TransportChildCv childCv = chlidCvMap.get(deployCar.getCarId());
            if (childCv == null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                msg.fail("操作失败，计划中的委托车未找到");
                return msg;
            }
            if (childCv.getBasicId() == null) {
                msg.fail("操作失败，无计划车架号请先录入计划");
                return msg;
            }
            TransportPlanCv planCv = planCvMap.get(childCv.getBasicId());
            if (planCv == null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                msg.fail("操作失败，计划不存在！");
                return msg;
            }
            boolean judge = false;
            //赋值当前位置
            childCv.setActualPositionId(deployCar.getDeliveryId());
            childCv.setActualPositionFullId(deployCar.getDeliveryFullId());
            childCv.setActualPositionName(deployCar.getDeliveryName());
            childCv.setActualPositionCoordinate(deployCar.getDeliveryCoordinate());
            if (deployDriver.getDeliveryType() == 1) { //港口交车
                childCv.setActualPortId(deployCar.getDeliveryPortId());
                childCv.setActualPortName(deployCar.getDeliveryPortName());
                judge = true;
            } else {
                childCv.setActualPortId(null);
                childCv.setActualPortName(null);
            }
            DateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date;
            try {
                date = ft.parse(newDeployDriver.getEndTime());
            } catch (Exception e) {
                date = null;
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                msg.fail("装车时间异常");
                return msg;
            }
            //比较交车地是否一致，一致则计划委托车完成  针对 计划 到达地类型：1区域，2港口    调配  0：区域 1：港口
            if ((deployCar.getDeliveryType() == 0 && deployCar.getDeliveryId().equals(childCv.getArrivePlaceId()) && childCv.getArrivePlaceType() == 1)
                    || (deployCar.getDeliveryType() == 1 && deployCar.getDeliveryPortId().equals(childCv.getArrivePortId()) && childCv.getArrivePlaceType() == 2)) {
                childCv.setState(3);
                if (newDeployDriver.getEndTime() != null) {
                    childCv.setDeliveryDate(date);
                } else {
                    childCv.setDeliveryDate(new Date());
                }
            } else {
                childCv.setState(0);
            }
            childCvs.add(childCv);
            uodateCarCvList.add(deployCar.getId());
        }
            //批量更新委托车
            if (uodateCarCvList.size() > 0) {
                carCvMapper.batchUpdateDeployCarCv(uodateCarCvList, deployDriver.getEndTime());
            }
            //更新计划委托车
            if (childCvs.size() > 0) {
                transportChildMapper.batchUpdatePlanCurrentLocation2(childCvs);
            }

        VehicleDeployFleetCv fleetCv = new VehicleDeployFleetCv();
        fleetCv.setStatus(2);
        fleetCv.setSurdownCount(deployDriver.getSurdownCount() +uodateCarCvList.size());
        fleetCvMapper.update(fleetCv, new QueryWrapper<VehicleDeployFleetCv>().eq("id", newDeployDriver.getId()));
        HighwaySupplierCar highwaySupplierCar = new HighwaySupplierCar();
        highwaySupplierCar.setStatus(0);
        highwaySupplierCarMapper.update(highwaySupplierCar, new QueryWrapper<HighwaySupplierCar>().eq("id", deployDriver.getTruckId()));
            //添加操作记录
            OperateRecord ope = new OperateRecord();
            ope.setId(RandomHelper.uuid());
            ope.setOperateType("卸车完成");
            ope.setSourceId(deployDriver.getId());
            if (empVo != null) {
                ope.setOperationName(empVo.getEmpNm());
                ope.setOperationId(empVo.getId());
            }
            operateRecordMapper.insert(ope);
            msg.success("操作成功");
            return msg;

    }
}
